﻿using System.Net.Mail;
using System.Text.RegularExpressions;
using System.Net;

namespace StampController.Core
{
    /// <summary>
    /// Summary description for SendMailClient
    /// </summary>
    public class SendMail
    {
        #region Constant

        private const int Port = 587;
        const string DisplayName = "Air Liquide";
        private const string Host = "smtp.gmail.com";
        const string EmailAddress = "info.dichvu@gmail.com";
        const string Password = "admin@info";

        //private const int Port = 25;
        //const string DisplayName = "Stamp Controller";
        //private const string Host = "smtp.as.corp.airliquide.com";
        //const string EmailAddress = "autoinfo@airliquide.com";
        //const string Password = "";

        #endregion

        #region define

        private SmtpClient _smtpClient;
        private MailAddress _mailFrom;

        public bool HasLogo { get; set; }
        public string LogoPath { get; set; }

        #endregion

        #region Constructors & Destructors
        public SendMail() : this(false) { }

        public SendMail(bool enableSSL)
            : this(Host, Port, DisplayName, EmailAddress, Password, enableSSL) { }

        public SendMail(string emailAddress, string password)
            : this(Host, Port, emailAddress, password) { }

        public SendMail(string emailAddress, string password, bool enableSSL)
            : this(Host, Port, emailAddress, password, enableSSL) { }

        public SendMail(string host, int port, string emailAddress, string password)
            : this(host, port, emailAddress, password, false) { }

        public SendMail(string host, int port, string emailAddress, string password, bool enableSSL)
            : this(host, port, DisplayName, emailAddress, password, enableSSL) { }

        public SendMail(string displayName, string emailAddress, string password)
            : this(Host, Port, displayName, emailAddress, password) { }

        public SendMail(string displayName, string emailAddress, string password, bool enableSSL)
            : this(Host, Port, displayName, emailAddress, password, enableSSL) { }

        public SendMail(string host, int port, string displayName, string emailAddress, string password)
            : this(host, port, displayName, emailAddress, password, false) { }

        public SendMail(string host, int port, string displayName, string emailAddress, string password, bool enableSSL)
        {
            InitializeMailClient(host, port, displayName, emailAddress, password, enableSSL);
        }

        #endregion

        #region Methods

        private void InitializeMailClient(string host, int port, string displayName, string emailAddress, string password, bool enableSSL)
        {
            _smtpClient = new SmtpClient(host, port)
            //{
            //    EnableSsl = false,
            //    Credentials = CredentialCache.DefaultNetworkCredentials,
            //    DeliveryMethod = SmtpDeliveryMethod.Network
            //};

            //bỏ chỗ này
            {
                DeliveryMethod = SmtpDeliveryMethod.Network,
                Credentials = new NetworkCredential(emailAddress, password),
                EnableSsl = enableSSL
            };

            _mailFrom = new MailAddress(emailAddress, displayName, System.Text.Encoding.UTF8);
        }

        public int Send(string emailTo, string subject, string body)
        {
            return Send(emailTo, subject, body, true, null, null);
        }

        public int Send(string emailTo, string subject, string body, bool isHTMLFormat)
        {
            return Send(emailTo, subject, body, isHTMLFormat, null, null);
        }

        public int Send(string emailTo, string subject, string body, string[] emailCc)
        {
            return Send(emailTo, subject, body, true, emailCc, null);
        }

        public int Send(string emailTo, string subject, string body, bool isHTMLFormat, string[] emailCC)
        {
            return Send(emailTo, subject, body, isHTMLFormat, emailCC, null);
        }

        public int Send(string emailTo, string subject, string body, string[] emailCc, string[] emailBcc)
        {
            return Send(emailTo, subject, body, true, emailCc, emailBcc);
        }

        /// <summary>
        /// Send Email
        /// </summary>
        /// <param name="emailTo"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        /// <param name="isHTMLFormat"></param>
        /// <param name="emailCC"></param>
        /// <param name="emailBcc"></param>
        /// <returns></returns>
        public int Send(string emailTo, string subject, string body, bool isHTMLFormat, string[] emailCC, string[] emailBcc)
        {
            try
            {
                // Validate Email
                var reg = new Regex(@"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$");

                if (reg.IsMatch(emailTo))
                {
                    var mailTo = new MailAddress(emailTo);

                    var mailMessage = new MailMessage(_mailFrom, mailTo);
                    mailMessage.ReplyToList.Add(_mailFrom);

                    // CC mails
                    if (emailCC != null && emailCC.Length > 0)
                    {
                        foreach (var item in emailCC)
                        {
                            if (string.IsNullOrEmpty(item)) continue;
                            mailMessage.CC.Add(new MailAddress(item));
                        }
                    }

                    // Bcc mails
                    if (emailBcc != null && emailBcc.Length > 0)
                    {
                        foreach (var item in emailBcc)
                        {
                            if(string.IsNullOrEmpty(item)) continue;
                            mailMessage.Bcc.Add(new MailAddress(item));
                        }
                    }

                    mailMessage.Subject = subject;
                    mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
                    mailMessage.IsBodyHtml = isHTMLFormat;

                    // specify the priority of the mail message
                    //mailMessage.Priority = MailPriority.High;
                    // This method has been deprecated.
                    // mail.Headers.Add("Return-Receipt-To", "prashantmx@xyz.com"); 
                    // Use this if you need an delivery notification of an email.             
                    // DeliveryNotificationOption is an enumeration
                    // and can be used to set the delivery notification on the following options:
                    // 1. Delay
                    // 2. Never
                    // 3. None
                    // 4. OnFailure
                    // 5. OnSuccess
                    // You can use also use OnFailure enum with OnSuccess enum. If in case the e-mail
                    // fails to delivered you'll get notification for both the cases
                    //mailMessage.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
                    // Add "Disposition-Notification-To" for Read receipt
                    //mailMessage.Headers.Add("Disposition-Notification-To", "");

                    AlternateView htmlView = AlternateView.CreateAlternateViewFromString(mailMessage.IsBodyHtml ? 
                        string.Format("<html><head><title>{0}</title></head><body>{1}</body></html>", subject, body) : body, null, "text/html");
                
                    if (HasLogo)
                    {
                        //const string filename = "Images/logo.jpg";
                        //string filePath = HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath.Replace("/", "\\")) + "\\" + filename;

                        //Creating LinkedSource for embedded picture
                        var myPhoto = new LinkedResource(LogoPath) {ContentId = "logo"};
                        //Adding LinkedSource to AlternateView
                        htmlView.LinkedResources.Add(myPhoto);
                    }

                    mailMessage.AlternateViews.Add(htmlView);

                    //mailMessage.Body = mailMessage.IsBodyHtml ? String.Format("<html><head><title>{0}</title></head><body>{1}</body></html>", subject, body) : body;

                    //ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
                    _smtpClient.Send(mailMessage);

                    return 1;
                }
                return 0;
            }
            catch
            {
                // Bug chỗ này coi nó báo gì rùi mới fix được
                return -1;
            }
        }
        #endregion

    }
}